#include "view.h"
#include "view_def.h"

/* ----- 事件回调的分发 ----- */

int32_t View::CallbackClick(ViewCallbackType type, int32_t x, int32_t y)
{
    /* 先检查子控件,且反序遍历(后面画的在上面) */
    for (View* cv = ChildEnd(); cv; cv = cv->Prev())
    {
        if (cv->OnCallback(type, x, y) == 0)
            return 0;
    }
    /* 再检查当前控件,命中则回调 */
    if (IsClickHit(x, y) && m_info.viewCallback)
    {
        m_info.viewCallback(this, type, m_info.priv);
        return 0;
    }
    /* 没有命中 */
    return 1;
}

int32_t View::CallbackZoom(ViewCallbackType type, int32_t x, int32_t y)
{
    /* 先缩放当前控件 */
    ActiveZoom(type == VCT_ZOOM_IN ? 1 : -1);
    /* 再正序缩放子控件,且正序遍历 */
    for (View* cv = ChildBegin(); cv; cv = cv->Next())
    {
        cv->OnCallback(type);
    }
    return 0;
}

int32_t View::CallbackState(ViewCallbackType type)
{
    switch (type)
    {
    case VCT_DISPLAY:
        return ActiveDisplay(true);
    case VCT_HIDE:
        return ActiveDisplay(false);

    case VCT_RESIZE:
        return ActiveResize();
    case VCT_DRAW:
        return ActiveDraw();

    case VCT_FOCUS_IN:
        return ActiveFocusIn(true);
    case VCT_FOCUS_OUT:
        return ActiveFocusIn(false);

    default:
        break;
    }
    return -1;
}

int32_t View::CallbackRelease(ViewCallbackType type)
{
    return 0;
}

/* ----- Active(动作预处理) ----- */

int32_t View::ActiveDisplay(bool yes)
{
    return 0;
}

int32_t View::ActiveResize()
{
    /* 自己是顶层控件时必定Resize,否则进行检查 */
    if (Parent() && !IsNeedResize())
        return -1;

    /* 计算位置范围 */
    Resize();

    /* 更新标志 */
    if (Parent())
        m_resizeFlag = Parent()->GetResizeFlag();
    else
        m_resizeFlag += 1;
    return 0;
}

int32_t View::ActiveDraw()
{
    /* 先计算范围 */
    int32_t ret = ActiveResize();

    /* 发生resize || crc32检查配置发生变化, 则重新绘图 */
    if (ret == 0 || IsNeedRedraw())
    {
        /* 绘图前回调 */
        if (m_info.viewCallback)
            m_info.viewCallback(this, VCT_DRAW, m_info.priv);

        /* 绘图 */
        Draw();

        /* 更新保存cr32值 */
        m_infoCrc32 = m_info.Crc32();
    }

    /* 画子控件 */
    for (View* cv = ChildBegin(); cv; cv = cv->Next())
    {
        /* 向下传递屏幕缓冲区 */
        cv->GetImageGrid() = m_imageGrid;

        cv->OnCallback(VCT_DRAW);
    }

    return 0;
}

int32_t View::ActiveFocusIn(bool yes)
{
    return 0;
}

int32_t View::ActiveZoom(int32_t zoom)
{
    return 0;
}

/* ----- 标志检查和判断 ----- */

bool View::IsClickHit(int32_t x, int32_t y)
{
    if (x < m_shapeX || x >= m_shapeX + m_shapeWidth)
        return false;
    if (y < m_shapeY || y > m_shapeY + m_shapeHeight)
        return false;
    return true;
}

bool View::IsNeedResize()
{
    /* flag和父控件不一致 */
    if (Parent() && Parent()->GetResizeFlag() != m_resizeFlag)
        return true;
    return false;
}

bool View::IsNeedRedraw()
{
    /* info中的数据发生变化 */
    return m_infoCrc32 == m_info.Crc32() ? false : true;
}
